//
//  JCDataCollectManager.m
//  ABookOfCartoon
//
//  Created by dlios on 15-5-25.
//  Copyright (c) 2015年 Power Of Ants. All rights reserved.
//

#import "JCDataCollectManager.h"

@implementation JCDataCollectManager
+(JCDataCollectManager *)shareInstance
{
    static JCDataCollectManager *dbManager = nil;
    if (dbManager == nil) {
        dbManager = [[JCDataCollectManager alloc]init];
    }
    return dbManager;
}
-(void)openDB
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *dbPath = [path stringByAppendingPathComponent:@"book2.db"];
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    NSLog(@"打开结果: %d, path: %@", result,dbPath);
}

-(void)createTable
{
    NSString *creatSQL = @"create table if not exists JCMainPageModel(BookName text  primary key, BookAuthor text, num integer)";
    int result = sqlite3_exec(dbPoint, creatSQL.UTF8String, NULL, NULL, nil);
    if (SQLITE_OK == result) {
        NSLog(@"成");
    }
    else{
        NSLog(@"败");
    }
}
-(void)insertInfowithJCMainPageModel:(JCMainPageModel *)page
{
    NSString *insertStr = [NSString stringWithFormat:@" insert into JCMainPageModel(BookName,BookAuthor)values('%@','%@')",page.BookName,page.BookAuthor];
    int result = sqlite3_exec(dbPoint, insertStr.UTF8String, NULL, NULL, nil);
    if (SQLITE_OK == result) {
        
        NSLog(@"插入了");
    }
    else{
        NSLog(@"没插进去");
    }
}
-(void)deleteInfowithName:(NSString *)bookName;
{
    //1.创建sql语句
    NSString *deleteSQL = [NSString stringWithFormat:@"delete from JCMainPageModel where BookName = '%@'",bookName];
    //2.执行语句
    int result = sqlite3_exec(dbPoint, deleteSQL.UTF8String, NULL, NULL, nil);
    //3.判断
    if (result == SQLITE_OK) {
        NSLog(@"删除了");
    }else
    {
        NSLog(@"没删掉");
    }
}

-(NSMutableArray *)selectInfo
{
    NSString *selectSQL = @"select * from JCMainPageModel";
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(dbPoint, selectSQL.UTF8String, -1, &stmt, nil);
    NSMutableArray *arr = [NSMutableArray array];
    if (SQLITE_OK == result) {
        NSLog(@"查成功");
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *name = sqlite3_column_text(stmt, 0);
            //int Author = sqlite3_column_int(stmt, 1);
            JCMainPageModel *temp = [[JCMainPageModel alloc]init];
            temp.BookName = [NSString stringWithUTF8String:(const char *)name];
            //temp.BookAuthor = [NSString stringWithFormat:@"%d",Author];
            //把Model对象添加在数组中
            [arr addObject:temp];
        }
    }
    return arr;
}

@end
